<?php
/**
 * Created by PhpStorm.
 * User: beijingwhg
 * Date: 2017/5/8
 * Time: 下午12:06
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\NotificationModel;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function notification(NotificationModel $notify)
    {
        $type = $this->request->get('type');
        //构建查询条件
        $where = [
            'id'    =>  admin()->admin_id,
            'to'    =>  'admin',
            'status'=>  '0',
        ];
        //查询
        if ($type == 'count') {
            $res = $notify->where($where)->count();
        } elseif($type == 'list') {
            $res = $notify->where($where)->take(5)->orderBy('created_at', 'desc')->get();
        }
        //返回结果
        return $this->ajaxReturn(10000, $res);
    }

    public function flagNotify(NotificationModel $notify)
    {
        $notId = false;

        if ($this->request->has('notid')) {
            $notId = $this->request->get('notid');
        }

        //构造条件
        $where = [
            'id'     => admin()->admin_id,
            'to'     => 'admin',
            'status' => '0'
        ];

        if ($notId) {
            $where['not_id'] = $notId;
        }

        //更新操作
        $res = $notify->where($where)->update(['status'=>1]);
        if ($res) {
            return $this->ajaxReturn(10000);
        } else {
            return $this->ajaxReturn();
        }
    }

    public function moreNotify(NotificationModel $notify)
    {
        $page = $this->request->get('page');

        $where = [
            'id'    =>  admin()->admin_id,
            'to'    =>  'admin'
        ];

        if (!$this->request->get('status')) {
            $where['status'] = '0';
        }

        $res = $notify->where($where)->offset($page*10)->limit(10)->get();

        if ($res) {
            return $this->ajaxReturn(10000, $res);
        } else {
            return $this->ajaxReturn();
        }
    }

    private function ajaxReturn($code = 0, $data = [])
    {
        return response()->json([
            'code'  =>  $code,
            'msg'   =>  config('error.'.$code),
            'data'  =>  $data
        ]);
    }
}